const router = require("koa-router")();

const ArticleBasic = require('../../model/ArticleBasic')
const isLine = require('is-online')
var Segment = require('segment');
// 创建实例
var segment = new Segment();
const axios = require('axios')
const url = 'http://ttapi.research.itcast.cn/app/v1_0/suggestion'
// 使用默认的识别模块及字典，载入字典文件需要1秒，仅初始化时执行一次即可

segment.useDefault();
// 获取搜索结果
router.get('/', async ctx  => {
    // 如果用户未登录 返回默认的频道数据
   const { q } = ctx.request.query
   if (!q) {
       return  { message: '搜索关键词不能为空', success: false, status: 400 }
   }
   try {
     // 检查网络状态
     await isLine()
     console.log('当前联网, 请求线上搜索建议接口')
     const { data: {  data: { options } } } = await axios({ url, params: { q }  })
     ctx.status = 200
     return { data: { options } }
    } catch (error) {
     console.log('当前断网, 执行线下搜索建议接口')
     let searchList = await ArticleBasic.find({ title: new RegExp(q) }, { title: 1 }).limit(10)
     searchList = searchList.map(item => item.title)
     let options = new Set()
     searchList.map(item => {
       const keywords = segment.doSegment(item).map(word => word.w).filter(word => word.split('').indexOf(q) > -1)
       options.add(...keywords) 
     })
     options = Array.from(options)
     return { data: { options } }
   }
  
})

module.exports = router.routes();
